package com.zf.shuashua.advert.hot;

import android.app.Activity;
import android.util.Log;

import com.qq.e.ads.cfg.VideoOption;
import com.qq.e.ads.nativ.ADSize;
import com.qq.e.ads.nativ.NativeExpressAD;
import com.qq.e.ads.nativ.NativeExpressADView;
import com.qq.e.ads.nativ.NativeExpressMediaListener;
import com.qq.e.comm.constants.AdPatternType;
import com.qq.e.comm.util.AdError;
import com.zf.shuashua.advert.AdReportManager;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.ReportConstants;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.manager.ActionThirdReportManager;
import com.zf.shuashua.utils.UIUtils;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 信息流广告--优量汇
 */
public class NativeTencentHotManager implements NativeExpressAD.NativeExpressADListener{

    private static final String TAG = "NativeAdvertManager";
    private static final int WIDTH_DEFAULT = 270;
    private static final int HEIGHT_DEFAULT = (int) (WIDTH_DEFAULT / 1.78);
    private NativeExpressAD nativeExpressAD;
    private String mAdvertType = AdvertConstants.NATIVE_TYPE_COMMON;
    private static NativeTencentHotManager instance;
    private WeakReference<Activity> weakReference;
    private HotTencentAdListener mListener;
    private String mCodeId = "7071747407734394";
    private int count = 1;

    private int width = WIDTH_DEFAULT;
    private int height = HEIGHT_DEFAULT;

    private String uuiThirdAdvert;
    private String planId;

    private NativeTencentHotManager() { }

    public static NativeTencentHotManager getInstance() {
        if (null == instance) {
            synchronized (NativeTencentHotManager.class) {
                if (null == instance) {
                    instance = new NativeTencentHotManager();
                }
            }
        }
        return instance;
    }

    /**
     * 宽度占满
     * @param activity
     * @param advertType
     * @param listener
     */
    public void loadFullExpressAd(Activity activity,  String advertType, String codeId, int count, HotTencentAdListener listener){
        mAdvertType = advertType;
        mCodeId = codeId;

//        this.width = ADSize.FULL_WIDTH;
//        this.height = ADSize.AUTO_HEIGHT;  this.width = (int) (UIUtils.getScreenWidthDp(activity) - 30);
        this.width = (int) UIUtils.getScreenWidthDp(activity);
        this.height = (int) (width / 1.78);
        this.count = count;

        loadExpressAd(activity,listener);
    }

    private void loadExpressAd(Activity activity, HotTencentAdListener listener){
        this.weakReference = new WeakReference<>(activity);
//        uuiThirdAdvert = Util.getUUID32();
        this.mListener = listener;

        nativeExpressAD = new NativeExpressAD(weakReference.get(), getMyADSize(), mCodeId, this);
        // 注意：如果您在平台上新建原生模板广告位时，选择了支持视频，那么可以进行个性化设置（可选）
        nativeExpressAD.setVideoOption(new VideoOption.Builder()
                .setAutoPlayPolicy(VideoOption.AutoPlayPolicy.ALWAYS) //自动播放视频
                .setAutoPlayMuted(true) // 自动播放时为静音
                .build());
        /**
         * 如果广告位支持视频广告，强烈建议在调用loadData请求广告前调用setVideoPlayPolicy，有助于提高视频广告的eCPM值
         * 如果广告位仅支持图文广告，则无需调用
         *
         * 设置本次拉取的视频广告，从用户角度看到的视频播放策略
         *
         * "用户角度"特指用户看到的情况，并非SDK是否自动播放，与自动播放策略AutoPlayPolicy的取值并非一一对应
         *
         * 如自动播放策略为AutoPlayPolicy.WIFI，但此时用户网络为4G环境，在用户看来就是手工播放的
         */
        nativeExpressAD.setVideoPlayPolicy(VideoOption.VideoPlayPolicy.AUTO);  // 本次拉回的视频广告，在用户看来是否为自动播放的
//        planId = System.identityHashCode(nativeExpressAD) + "";

        nativeExpressAD.loadAD(count);
        reportRequestStart();
    }


    private ADSize getMyADSize() {
        return new ADSize(width, height);
    }

    private void reportRequestStart(){
        ActionThirdReportManager.getInstance().reportRequestStart(2, 4, mCodeId, count);
    }

    private void reportRequestSucc(int return_num) {
        ActionThirdReportManager.getInstance().reportRequestSucc(2, 4, mCodeId, return_num);
    }

    private void reportRequestFail(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestFail(2, 4, mCodeId, count, error_code, error_msg);
    }

    private void reportRequestRend(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestRend(2, 4, mCodeId, error_code, error_msg);
    }

    @Override
    public void onNoAD(AdError adError) {
        weakReference.get().runOnUiThread(() -> {
            if(mListener != null){
                mListener.onNoAD(adError);
            }
        });
        if(adError != null){
            reportRequestFail(adError.getErrorCode() + "", adError.getErrorMsg());
        }
//        Log.i(
//                TAG,
//                String.format("onNoAD, error code: %d, error msg: %s", adError.getErrorCode(),
//                        adError.getErrorMsg()));
    }

    @Override
    public void onADLoaded(List<NativeExpressADView> adList) {
//        Log.i(TAG, "onADLoaded: " + adList.size());

        if(adList == null || adList.size() < 1){
            return;
        }
        for (NativeExpressADView nativeExpressADView: adList) {
            if (nativeExpressADView.getBoundData().getAdPatternType() == AdPatternType.NATIVE_VIDEO) {
                nativeExpressADView.setMediaListener(mediaListener);
            }
            nativeExpressADView.render();
        }
//        nativeExpressADView.render();
        if(mListener != null){
            mListener.onADLoaded(adList);
        }
        reportRequestSucc(adList.size());
//        if(mListener != null){
//            mListener.onRenderSuccess(nativeExpressADView);
//        }
        // 广告可见才会产生曝光，否则将无法产生收益。
//        container.addView(nativeExpressADView);
    }

    @Override
    public void onRenderFail(NativeExpressADView adView) {
//        Log.i(TAG, "onRenderFail");
//        weakReference.get().runOnUiThread(() -> {
//            if(mListener != null){
//                mListener.onError();
//            }
//        });
        reportRequestRend("10", "render fail");
    }

    @Override
    public void onRenderSuccess(NativeExpressADView adView) {
//        if(mListener != null){
//            mListener.onRenderSuccess(adView);
//        }
        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageShow, getReportType(), "2");
//        Log.i(TAG, "onRenderSuccess");
    }

    @Override
    public void onADExposure(NativeExpressADView adView) {
//        Log.i(TAG, "onADExposure");
    }

    @Override
    public void onADClicked(NativeExpressADView adView) {
//        Log.i(TAG, "onADClicked" + adView.ext.get("clickUrl"));
        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageClick, getReportType(), "2");
    }

    @Override
    public void onADClosed(NativeExpressADView adView) {
//        Log.i(TAG, "onADClosed");
        // 当广告模板中的关闭按钮被点击时，广告将不再展示。NativeExpressADView也会被Destroy，释放资源，不可以再用来展示。
//        if (container != null && container.getChildCount() > 0) {
//            container.removeAllViews();
//            container.setVisibility(View.GONE);
//        }
    }

    @Override
    public void onADLeftApplication(NativeExpressADView adView) {
//        Log.i(TAG, "onADLeftApplication");
    }

    @Override
    public void onADOpenOverlay(NativeExpressADView adView) {
//        Log.i(TAG, "onADOpenOverlay");
    }

    @Override
    public void onADCloseOverlay(NativeExpressADView adView) {
//        Log.i(TAG, "onADCloseOverlay");
    }

    private NativeExpressMediaListener mediaListener = new NativeExpressMediaListener() {
        @Override
        public void onVideoInit(NativeExpressADView nativeExpressADView) {
//            Log.i(TAG, "onVideoInit: "
//                    + getVideoInfo(nativeExpressADView.getBoundData().getProperty(AdData.VideoPlayer.class)));
        }

        @Override
        public void onVideoLoading(NativeExpressADView nativeExpressADView) {
//            Log.i(TAG, "onVideoLoading");
        }

        @Override
        public void onVideoCached(NativeExpressADView adView) {
//            Log.i(TAG, "onVideoCached");
//            // 视频素材加载完成，此时展示视频广告不会有进度条。
//            if(isPreloadVideo && nativeExpressADView != null) {
//                if(container.getChildCount() > 0){
//                    container.removeAllViews();
//                }
//                // 广告可见才会产生曝光，否则将无法产生收益。
//                container.addView(nativeExpressADView);
//                nativeExpressADView.render();
//            }
        }

        @Override
        public void onVideoReady(NativeExpressADView nativeExpressADView, long l) {
            Log.i(TAG, "onVideoReady");
        }

        @Override
        public void onVideoStart(NativeExpressADView nativeExpressADView) {
//            Log.i(TAG, "onVideoStart: "
//                    + getVideoInfo(nativeExpressADView.getBoundData().getProperty(AdData.VideoPlayer.class)));
        }

        @Override
        public void onVideoPause(NativeExpressADView nativeExpressADView) {
//            Log.i(TAG, "onVideoPause: "
//                    + getVideoInfo(nativeExpressADView.getBoundData().getProperty(AdData.VideoPlayer.class)));
        }

        @Override
        public void onVideoComplete(NativeExpressADView nativeExpressADView) {
//            Log.i(TAG, "onVideoComplete: "
//                    + getVideoInfo(nativeExpressADView.getBoundData().getProperty(AdData.VideoPlayer.class)));
        }

        @Override
        public void onVideoError(NativeExpressADView nativeExpressADView, AdError adError) {
//            Log.i(TAG, "onVideoError");
//            weakReference.get().runOnUiThread(() -> {
//                if(mListener != null){
//                    mListener.onError();
//                }
//            });
        }

        @Override
        public void onVideoPageOpen(NativeExpressADView nativeExpressADView) {
//            Log.i(TAG, "onVideoPageOpen");
        }

        @Override
        public void onVideoPageClose(NativeExpressADView nativeExpressADView) {
//            Log.i(TAG, "onVideoPageClose");
        }
    };

    private String getReportType(){
        String type = ReportConstants.NATIVE_TYPE_COMMON;
        switch (mAdvertType) {
            case AdvertConstants.NATIVE_TYPE_COMMON:
                type = ReportConstants.NATIVE_TYPE_COMMON;
                break;
            case AdvertConstants.NATIVE_TYPE_BUBBLE:
                type = ReportConstants.NATIVE_TYPE_BUBBLE;
                break;
            case AdvertConstants.NATIVE_TYPE_ENCOURAGE:
                type = ReportConstants.NATIVE_TYPE_ENCOURAGE;
                break;
            case AdvertConstants.NATIVE_TYPE_WITHDRAW:
                type = ReportConstants.NATIVE_TYPE_WITHDRAW;
                break;
        }
        return type;
    }

    private String getCodeId(){
        String codeId = "2061612381617032";
        switch (mAdvertType) {
            case AdvertConstants.NATIVE_TYPE_COMMON:
                codeId = "2061612381617032";
                break;
            case AdvertConstants.NATIVE_TYPE_BUBBLE:
                codeId = "1011210331910033";
                break;
            case AdvertConstants.NATIVE_TYPE_ENCOURAGE:
                codeId = "3091214301517056";
//                codeId = "9021820060589336";
                break;
            case AdvertConstants.NATIVE_TYPE_WITHDRAW:
                codeId = "5081111331617090";
                break;
            case AdvertConstants.NATIVE_TYPE_HOT:
                codeId = "7071747407734394";
                break;
        }
        return codeId;
    }

}
